package com.easemob.chatuidemo.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import android.annotation.SuppressLint;
import android.util.Log;

@SuppressLint("NewApi")
public class JSONUtil {
    private static final String TAG = "JSONUtil";
    
    
    /**
     * 获取JSON内容
     * @param reqType·接口
     * @param reqData·参数
     * @return
     * @throws JSONException
     * @throws Exception
     */
    public static JSONObject getJSON(String reqType,JSONObject reqData) throws JSONException, Exception {
        String result = getRequest(reqType,reqData);
        if (result == null) {
            return null;
        }
        return new JSONObject(result);
    }
    
    protected static String getRequest(String reqType,JSONObject reqData) throws Exception {
        Map<String, String> map=new HashMap<String, String>();
        map = parserToMap(reqData);
        return getRequest(reqType,map, "UTF-8");
    }
    
    private static String getRequest(String path, Map<String, String> reqData, String encoding) throws Exception{
        String result = "";
        StringBuilder sb = new StringBuilder(path);
        if (reqData != null && !reqData.isEmpty()) {
            sb.append("?");
            for (Map.Entry<String, String> entry : reqData.entrySet()) {
                sb.append(entry.getKey()).append("=");
                sb.append(URLEncoder.encode(entry.getValue(),encoding));
                sb.append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            Log.i(TAG, "URLpath==========" + sb);
        }
        
        HttpURLConnection conn = (HttpURLConnection) new URL(sb.toString()).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            result = getStringFromInputStream(is);
            System.out.println(result);
        }
        return result;
        
    }
    
    public static JSONArray getRequest(String path, String telList){
        String url = path + "?loginnames=" + telList;
        String result = "";
        JSONArray array = new JSONArray();
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                InputStream is = conn.getInputStream();
                result = getStringFromInputStream(is);
                System.out.println(result);
                array = new JSONArray(result);
            }
        } catch (Exception e) {
            Log.i(TAG, "JSON错误:" + e.getMessage());
            e.printStackTrace();
        }
        return array;
    }

    public static JSONArray getNearby(String path,JSONObject reqData) throws Exception {
        JSONArray array = new JSONArray();
        Map<String, String> map=new HashMap<String, String>();
        map = parserToMap(reqData);

        StringBuilder sb = new StringBuilder(path);
        if (map != null && !map.isEmpty()) {
            sb.append("?");
            for (Map.Entry<String, String> entry : map.entrySet()) {
                sb.append(entry.getKey()).append("=");
                sb.append(URLEncoder.encode(entry.getValue(),"UTF-8"));
                sb.append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            Log.i(TAG, "URLpath==========" + sb);
        }

        HttpURLConnection conn = (HttpURLConnection) new URL(sb.toString()).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            String result = getStringFromInputStream(is);
            System.out.println(result);
            array = new JSONArray(result);
        }

        return array;
    }
    
    
    private static String getStringFromInputStream(InputStream is) throws Exception{
        
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        byte[] buff=new byte[1024];
        int len=-1;
        while((len=is.read(buff))!=-1){
            baos.write(buff, 0, len);
        }
        is.close();
        String html=baos.toString();
        baos.close();
        return html;
    }
    
    
    public static Map<String, String> parserToMap(JSONObject json) throws Exception{
        Map<String, String> map=new HashMap<String, String>();
//        JSONObject json=(JSONObject) JSONObject.wrap(s);  
        Iterator keys=json.keys();  
        while(keys.hasNext()){  
            String key=(String) keys.next();  
            String value=json.get(key).toString();  
            if(value.startsWith("{")&&value.endsWith("}")){
                map.put(key, value);
            }else{  
                map.put(key, value);  
            }  
      
        }  
        return map;  
    }
    
//    public static Map<String, Object> parseJSON2Map(String jsonStr){  
//        Map<String, Object> map = new HashMap<String, Object>();  
//        //最外层解析  
//        JsonObject obj = new JsonObject();
//        JsonObject json = obj.getAsJsonObject(jsonStr);
//        for(Object k : json.entrySet()){  
//            Object v = json.ge   
//            //如果内层还是数组的话，继续解析  
//            if(v instanceof JsonArray){  
//                List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();  
//                Iterator<JSONObject> it = ((JSONArray)v).iterator();  
//                while(it.hasNext()){  
//                    JSONObject json2 = it.next();  
//                    list.add(parseJSON2Map(json2.toString()));  
//                }  
//                map.put(k.toString(), list);  
//            } else {  
//                map.put(k.toString(), v);  
//            }  
//        }  
//        return map;  
//    }  

}
